﻿using JNPF.Basics.Models;
using JNPF.Basics.Models.WorkFlow.Model;
using JNPF.Data;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace JNPF.Basics.Logic.WorkFlow.FlowFlowDynamic
{
    public class FlowFlowDynamicService : DataFactory, FlowFlowDynamicIService
    {
        public void Create(Dictionary<string, object> allDataDic, Dictionary<string, object> newMainDataDic, string id, FlowEngineEntity entity)
        {
            using (var db = this.Basic)
            {
                //生成一个主表Id
                var mainId = id;
                var formData = entity.FormTemplateJson.ToObject<FormDataModel>();
                var modelList = formData.fields.ToList<FieldsModel>();
                var tableMapList = entity.Tables.ToList<Dictionary<string, object>>();
                //主表字段集合
                var mainFelid = new StringBuilder();
                var mainFelidList = new List<string>();
                //主表查询语句
                var mainSql = new StringBuilder();
                var allAddSql = new StringBuilder();
                foreach (var model in modelList)
                {
                    if ("table".Equals(model.__config__.jnpfKey))
                    {
                        //遍历所有数据寻找子表
                        foreach (var item in newMainDataDic)
                        {
                            if (item.Key.Equals(model.__vModel__) && item.Value != null)
                            {
                                var feilds = new StringBuilder();
                                var childModelList = model.__config__.children;
                                foreach (var tableMap in tableMapList)
                                {
                                    if (tableMap["table"].ToString().Equals(model.__config__.tableName))
                                    {
                                        feilds.Append(tableMap["tableField"].ToString() + ",");
                                    }
                                }
                                foreach (var tableMap in tableMapList)
                                {
                                    if (tableMap["table"].ToString().Equals(model.__config__.tableName))
                                    {
                                        foreach (var model1 in childModelList)
                                        {
                                            feilds.Append(model1.__vModel__ + ",");
                                        }
                                    }
                                }
                                if (childModelList.Count > 0)
                                {
                                    feilds.Remove(feilds.Length - 1, 1);
                                }
                                //查询子表数据sql
                                var childSql = new StringBuilder();
                                childSql.Append("insert into " + model.__config__.tableName + "(F_Id," + feilds + ") " + " values ");
                                foreach (var tableMap in tableMapList)
                                {
                                    if (tableMap["table"].ToString().Equals(model.__config__.tableName))
                                    {
                                        var childList = allDataDic[item.Key].ToString().ToList<Dictionary<string, object>>();
                                        foreach (var childMap in childList)
                                        {
                                            childSql.Append("('" + CommonHelper.Guid + "','" + mainId + "',");
                                            foreach (var model1 in childModelList)
                                            {
                                                //判断字段值是否为空
                                                if (!childMap.ContainsKey(model1.__vModel__))
                                                {
                                                    childSql.Append(null + ",");
                                                }
                                                else
                                                {
                                                    childSql.Append("'" + childMap[model1.__vModel__].ToString() + "',");
                                                }
                                            }
                                            childSql.Remove(childSql.Length - 1, 1);
                                            childSql.Append("),");
                                        }
                                        childSql.Remove(childSql.Length - 1, 1);
                                        var childSqlx = childSql.ToString();
                                        childSqlx.Replace(",'\\)", ")");
                                        allAddSql.Append(childSqlx + ";");
                                        //清除子表字段
                                        allDataDic.Remove(item.Key);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        //添加主表查询字段
                        mainFelid.Append(model.__vModel__ + ",");
                        mainFelidList.Add(model.__vModel__);
                    }
                }
                mainFelid.Remove(mainFelid.Length - 1, 1);
                mainSql.Append("insert into " + tableMapList[0]["table"].ToString() + "(F_Id," + mainFelid.ToString() + ") " + " values ('" + mainId + "',");
                //调整字段与值的顺序
                foreach (var mainModel in modelList)
                {
                    foreach (var mainStr in mainFelidList)
                    {
                        if (mainStr.Equals(mainModel.__vModel__))
                        {
                            //判断字段值是否为空
                            if (!allDataDic.ContainsKey(mainModel.__vModel__))
                            {
                                mainSql.Append(null + ",");
                            }
                            else
                            {
                                if (allDataDic[mainModel.__vModel__] != null)
                                {
                                    mainSql.Append("'" + allDataDic[mainModel.__vModel__] + "',");
                                }
                                else
                                {
                                    mainSql.Append(null + ",");
                                }
                            }
                        }
                    }
                }
                mainSql.Remove(mainSql.Length - 1, 1);
                mainSql.Append(");");
                allAddSql.Append(mainSql);
                db.ExecuteSql(allAddSql.ToString());
            }
        }

        public Dictionary<string, object> GetInfo(FlowEngineEntity entity, string id)
        {
            using (var db = this.Basic)
            {
                List<Dictionary<string, object>> tableMapList = entity.Tables.ToList<Dictionary<string, object>>();
                var mainfeild = new StringBuilder();
                var main = string.Join("select * from {0} where F_Id='{1}'", tableMapList[0]["table"].ToString(), id);
                //mainfeild.Append(sqltxt);
                List<Dictionary<string, object>> mainMap = this.getTableDataInfo(main);
                //记录全部主表数据
                var dataMap = mainMap[0];
                //记录列表展示的主表数据
                Dictionary<string, object> formData = entity.FormTemplateJson.ToObject<Dictionary<string, object>>();
                var modelList = formData["fields"].ToString().ToList<FieldsModel>();
                var newDataMap = new Dictionary<string, object>();
                foreach (var item in modelList)
                {
                    if (item.__config__.jnpfKey == "table")
                    {
                        var feilds = new StringBuilder();
                        var childModelList = item.__config__.children;
                        foreach (var childModel in childModelList)
                        {
                            feilds.Append(childModel.__vModel__ + ",");
                        }
                        if (childModelList.Count > 0)
                        {
                            feilds.Remove(feilds.Length - 1, 1);
                        }
                        //子表字段
                        string relationFeild = "";
                        //主表字段
                        string relationMainFeild = "";
                        string relationMainFeildValue = "";
                        //查询子表数据
                        StringBuilder childSql = new StringBuilder();
                        childSql.Append("select " + feilds + " from" + " " + item.__config__.tableName + " where 1=1");
                        foreach (var tableMap in tableMapList)
                        {
                            if (tableMap["table"].ToString() == item.__config__.tableName)
                            {
                                relationFeild = tableMap["tableField"].ToString();
                                relationMainFeild = tableMap["relationField"].ToString();
                                if (dataMap.ContainsKey(relationMainFeild))
                                {
                                    relationMainFeildValue = dataMap["relationMainFeild"].ToString();
                                    childSql.Append(" And " + relationFeild + "='" + relationMainFeildValue + "'");
                                }
                                newDataMap.Add(item.__vModel__, getTableDataInfo(childSql.ToString()));
                            }
                        }
                    }
                    else
                    {
                        mainfeild.Append(item.__vModel__ + ",");
                    }
                }
                if (modelList.Count > 0)
                {
                    mainfeild.Remove(mainfeild.Length - 1, 1);
                }
                foreach (var fieldsModel in modelList)
                {
                    foreach (var entryMap in dataMap.Keys)
                    {
                        if (fieldsModel.__vModel__ == entryMap)
                        {
                            if (mainfeild.ToString().Equals(entryMap))
                            {
                                if ("uploadFz".Equals(fieldsModel.__config__.jnpfKey) || "uploadImg".Equals(fieldsModel.__config__.jnpfKey))
                                {
                                    //附件
                                    var map = dataMap[entryMap].ToString().ToList<Dictionary<string, object>>();
                                    newDataMap.Add(entryMap, map);
                                }
                                else if ("checkbox".Equals(fieldsModel.__config__.jnpfKey) || "cascader".Equals(fieldsModel.__config__.jnpfKey))
                                {
                                    //级联、多选
                                    var list = dataMap[entryMap].ToObject<List<string>>();
                                    newDataMap.Add(entryMap, list);
                                }
                                else
                                {
                                    newDataMap.Add(entryMap, dataMap[entryMap]);
                                }
                            }
                        }
                    }
                }
                return newDataMap;
            }
        }

        public void Update(Dictionary<string, object> allDataDic, Dictionary<string, object> newMainDataDic, string id, FlowEngineEntity entity)
        {
            using (var db = this.Basic)
            {
                var tableMapList = entity.Tables.ToList<Dictionary<string, object>>();
                //循环表
                var delMain = "delete from " + tableMapList[0]["table"] + " where F_Id='" + id + "'";
                var allDelSql = new StringBuilder();
                allDelSql.Append(delMain + ";");

                var queryMain = "select * from" + " " + tableMapList[0]["table"] + " where F_Id='" + id + "'";
                var mainMapList = getTableDataInfo(queryMain);
                if (mainMapList.Count > 0)
                {
                    if (tableMapList.Count > 0)
                    {
                        //去除主表,剩余的为子表，再进行子表删除语句生成
                        tableMapList.Remove(tableMapList[0]);
                        foreach (var tableMap in tableMapList)
                        {
                            //主表字段
                            var relationField = tableMap["relationField"].ToString();
                            var relationFieldValue = mainMapList[0][relationField].ToString();
                            //子表字段
                            var tableField = tableMap["tableField"].ToString();
                            var childSql = "delete from " + tableMap["table"].ToString() + " where " + tableField + "='" + relationFieldValue + "'";
                            allDelSql.Append(childSql + ";");
                        }
                    }
                    //添加数据
                    //生成一个主表Id
                    var mainId = id;
                    var tableMapList1 = entity.Tables.ToString().ToList<Dictionary<string, object>>();
                    var columnData = entity.FormTemplateJson.ToObject<Dictionary<string, object>>();
                    var modelList = columnData["fields"].ToString().ToList<FieldsModel>();
                    //主表字段集合
                    var mainFelid = new StringBuilder();
                    var mainFelidList = new List<string>();
                    //主表查询语句
                    var mainSql = new StringBuilder();
                    var allAddSql = new StringBuilder();
                    foreach (var model in modelList)
                    {
                        if ("table".Equals(model.__config__.tableName))
                        {
                            //遍历所有数据寻找子表
                            foreach (var iterator in newMainDataDic)
                            {
                                var key = iterator.Key;
                                //判断子表是否有数据
                                if (key.Equals(model.__vModel__) && newMainDataDic[key] != null)
                                {
                                    var feilds = new StringBuilder();
                                    var childModelList = model.__config__.children;
                                    foreach (var tableMap in tableMapList1)
                                    {
                                        if (tableMap["table"].ToString().Equals(model.__config__.tableName))
                                        {
                                            feilds.Append(tableMap["tableField"].ToString() + ",");
                                        }
                                    }
                                    foreach (var tableMap in tableMapList1)
                                    {
                                        if (tableMap["table"].ToString().Equals(model.__config__.tableName))
                                        {
                                            foreach (var model1 in childModelList)
                                            {
                                                feilds.Append(model1.__vModel__ + ",");
                                            }
                                        }
                                    }
                                    if (childModelList.Count > 0)
                                    {
                                        feilds.Remove(feilds.Length - 1, 1);
                                    }
                                    //查询子表数据sql
                                    var childSql = new StringBuilder();
                                    childSql.Append("insert into " + model.__config__.tableName + "(F_Id," + feilds + ") " + " values ");
                                    foreach (var tableMap in tableMapList1)
                                    {
                                        if (tableMap["table"].ToString().Equals(model.__config__.tableName))
                                        {
                                            var childList = allDataDic[key].ToString().ToList<Dictionary<string, object>>();
                                            foreach (var childMap in childList)
                                            {
                                                childSql.Append("('" + CommonHelper.Guid + "','" + mainId + "',");
                                                foreach (var model1 in childModelList)
                                                {
                                                    //判断字段值是否为空
                                                    if (!childMap.ContainsKey(model1.__vModel__))
                                                    {
                                                        childSql.Append(null + ",");
                                                    }
                                                    else
                                                    {
                                                        childSql.Append("'" + childMap[model1.__vModel__].ToString() + "',");
                                                    }
                                                }
                                                childSql.Remove(childSql.Length - 1, 1);
                                                childSql.Append("),");
                                            }
                                            childSql.Remove(childSql.Length - 1, 1);
                                            var childSqlx = childSql.ToString();
                                            childSqlx = childSqlx.Replace(",'\\)", ")");
                                            allAddSql.Append(childSqlx + ";");
                                            //清除子表字段
                                            allDataDic.Remove(key);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //添加主表查询字段
                            mainFelid.Append(model.__vModel__ + ",");
                            mainFelidList.Add(model.__vModel__);
                        }
                    }
                    mainFelid.Remove(mainFelid.Length - 1, 1);
                    mainSql.Append("insert into " + tableMapList1[0]["table"] + "(F_Id," + mainFelid.ToString() + ") " + " values ('" + mainId + "',");
                    //调整字段与值的顺序
                    foreach (var mainModel in modelList)
                    {
                        foreach (var mainStr in mainFelidList)
                        {
                            if (mainStr.Equals(mainModel.__vModel__))
                            {
                                //判断字段值是否为空
                                if (!allDataDic.ContainsKey(mainModel.__vModel__))
                                {
                                    mainSql.Append(null + ",");
                                }
                                else
                                {
                                    if (allDataDic[mainModel.__vModel__] != null)
                                    {
                                        mainSql.Append("'" + allDataDic[mainModel.__vModel__] + "',");
                                    }
                                    else
                                    {
                                        mainSql.Append(null + ",");
                                    }
                                }
                            }
                        }
                    }
                    mainSql.Remove(mainSql.Length - 1, 1);
                    mainSql.Append(");");
                    allAddSql.Append(mainSql);
                    db.ExecuteSql(allDelSql.ToString() + allAddSql.ToString());
                }
                else
                {
                    throw new Exception("更新失败，数据不存在");
                }
            }

        }

        #region Method
        public List<Dictionary<string, object>> getTableDataInfo(string sql)
        {
            using (var db = this.Basic)
            {
                var data = db.GetTableSql(sql);
                var output = UtilConvert.DataTableToDicList(data);
                return output;
            }
        }

        public Dictionary<string, object> getMast(string sql)
        {
            using (var db = this.Basic)
            {
                var dt = db.GetTableSql(sql);
                var output = UtilConvert.DataTableToDic(dt);
                return output;
            }
        }

        public void opaTableDataInfo(string sql)
        {
            using (var db = this.Basic)
            {
                var flag = db.ExecuteSql(sql);
            }
        }

        public static List<T> DataTableToList<T>(DataTable table)
        {
            if (table == null || table.Rows.Count == 0)
                return new List<T>();

            List<T> list = new List<T>();
            T model = default(T);
            foreach (DataRow dr in table.Rows)
            {
                model = Activator.CreateInstance<T>();
                foreach (DataColumn dc in dr.Table.Columns)
                {
                    object drValue = dr[dc.ColumnName];
                    PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName);
                    if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
                    {
                        pi.SetValue(model, drValue.ToString(), null);
                    }
                }
                list.Add(model);
            }
            return list;
        }
        #endregion
    }
}
